package com.k7k7.client;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

public abstract class BaseClient extends Thread {
	protected Logger log = Logger.getLogger(getClass());
	protected BufferedReader reader;
	protected PrintWriter writer;
	private Socket socket;
	protected Element sendPac;

	public BaseClient(Socket client) throws Exception {
		this.socket = client;
		try {
			reader = new BufferedReader(new InputStreamReader(socket
					.getInputStream(), Charset.forName("UTF-8")));
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream(), Charset.forName("UTF-8"))), true);
		} catch (Exception e) {
			try {
				if (reader != null) {
					reader.close();
				}
				if (writer != null) {
					writer.close();
				}
				socket.close();
			} catch (Exception ee) {
			}
			throw new Exception("reader or writer init error");
		}
	}

	@Override
	public void run() {
		String input = "";
		try {
			while (true) {
				input = reader.readLine().trim();
				if (null == input || input.equals("")) {
					continue;
				}
				receive(input);
			}
		} catch (Exception e) {
			log.info("接收信息时出错");
			try {
				socket.close();
				reader.close();
				writer.close();
			} catch (Exception ignored) {
			}
			this.startError();
		}
	}

	public void send(Element doc) {
		Element ret;
		if (this.sendPac != null) {
			this.sendPac.add((Element) doc.clone());
			ret = (Element) sendPac.clone();
		} else {
			ret = doc;
		}
		log.info("send-->" + ret.asXML());
		if (writer != null) {
			writer.println(ret.asXML() + "\0");
		}
		this.sendPac = null;
	}

	/**
	 * 离开社区
	 */
	public abstract void startError();

	/**
	 * 处理消息
	 *
	 * @param input
	 */
	private void receive(String input) {
		Document doc;
		try {
			doc = DocumentHelper.parseText(input);
		} catch (DocumentException e1) {
			log.error("解析XML错误:" + input);
			return;
		}
		Element root = doc.getRootElement();
		log.info(root.asXML());
		this.handleMsg((Element) root.clone());
		log.info("----------------");
	}

	public abstract void handleMsg(Element ele);
}
